package com.wanxing.main;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.util.HttpUtils;
import com.util.Info;
import com.util.UIHelper;
import com.zhny.wxginger.R;
import com.zhny.handler.Sendcommand;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import customview.LineChartView;
import vo.DTU_data;
import vo.DTU_inf;
import vo.LineChartData;

import static com.util.HttpUtils.sendPostMethod;
import static com.util.Info.path9;

public class DataShowFragment extends Fragment {
    private TextView title;
    private View mView;
    private TextView d_odate;
    private TextView d_otime;
    private ImageButton d_refresh;

    private ListView listView;
    private LineChartView lineChartView;
    private SimpleAdapter adapter;

    private ArrayList<HashMap<String, Object>> list;
    private int[] imageResId;
    private String type;
    private String dtu;
    private String unit;
    private DTU_data dtu_data = new DTU_data();
    private DTU_inf dtu_inf = new DTU_inf();
    private Handler handler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        mView = inflater.inflate(R.layout.data_show, container, false);

        init();

        return mView;

    }

    //实例化控件  设置首选URL
    private void init() {
//        d_odtu = (TextView) mView.findViewById(R.id.d_dtu);
//        d_otype = (TextView) mView.findViewById(R.id.d_type);
//        d_ocrops = (TextView) mView.findViewById(R.id.d_crops);
//        d_ostage = (TextView) mView.findViewById(R.id.d_stage);
        d_otime = (TextView) mView.findViewById(R.id.d_time);
        d_odate = (TextView) mView.findViewById(R.id.d_date);
        listView = (ListView) mView.findViewById(R.id.data_listview);
        d_refresh = (ImageButton) mView.findViewById(R.id.d_refresh);

        //点击item 获取 type dtu unit
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                type = list.get(position).get("Dname").toString().trim();  // type
                dtu = getActivity().getActionBar().getTitle().toString().trim(); // dtu
                unit = list.get(position).get("Dunit").toString().trim();  // unit
                type = changeTYPE(type);
                if (type == null)
                {
                    Toast.makeText(getActivity(), "错误", Toast.LENGTH_SHORT).show();
                }
                //设置地址
                String url = setURL(type, dtu, 7);
                Toast.makeText(getActivity(), "点击 " + type + " " + dtu + " " + unit, Toast.LENGTH_SHORT).show();
                //异步加载  showDialog(type,unit,);
                new lineAsyncTask().execute(url + "~" + type + "~" + unit);
            }
        });

        //登录首选地址
        String plotid = getActivity().getActionBar().getTitle().toString();

        String url2 = Info.pathQueryData + "?plotid=" + plotid;
        new MyDTUDataAsyncTask().execute(url2);

        d_refresh.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                String plotid = getActivity().getActionBar().getTitle().toString();
                String url2 = Info.pathQueryData + "?plotid=" + plotid;

                //指令到底是啥
                String command = "BB00dezhoulx" + plotid + "EF";

                System.out.println(command);
                new Thread(new Sendcommand(handler, command)).start();

                new UIHelper().showDialogForLoading(getActivity(), "正在上传新数据，请等待10秒", true);
                new freshAsyncTask().execute(url2);
            }
        });
    }


    // DTU_data 异步加载 大棚列表数据
    public class MyDTUDataAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... arg0) {
            System.out.println(arg0[0] + "      DTU_data 异步加载");
            return sendPostMethod(arg0[0], "utf-8");
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result == null) {
                dtu_data = new DTU_data(null, null, null, null, null, null,
                        null, null, null, null, null,null,null, null,null,
                        null,null, null,null,null,null, null);

                Toast.makeText(getActivity(), "连接 失败", Toast.LENGTH_SHORT).show();
            } else {

                dtu_data = jsonMyDTUData(result);
                list = getItem(dtu_data);
            }
            adapter = new SimpleAdapter(getActivity(), list,
                    R.layout.data_show_item, new String[]{"Dimg", "Dname",
                    "Ddate", "Dunit"}, new int[]{
                    R.id.data_imageView1, R.id.data_name,
                    R.id.data_vaule, R.id.data_unit});
            listView.setAdapter(adapter);

        }

    }
    // 异步加载 刷新数据



    public class freshAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strings) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("开始获取数据");
            String result = HttpUtils.sendPostMethod(strings[0], "utf-8");
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new UIHelper().hideDialogForLoading();
            if (result == null)
            {
                dtu_data = new DTU_data(null, null, null, null, null, null,
                        null, null, null, null, null,null,null, null,null,
                        null,null, null,null,null,null, null);
                Toast.makeText(getActivity(), "连接 失败", Toast.LENGTH_SHORT).show();
            } else {

                dtu_data = jsonMyDTUData(result);
                list = getItem(dtu_data);
            }
            adapter = new SimpleAdapter(getActivity(), list,
                    R.layout.data_show_item, new String[]{"Dimg", "Dname",
                    "Ddate", "Dunit"}, new int[]{
                    R.id.data_imageView1, R.id.data_name,
                    R.id.data_vaule, R.id.data_unit});
            listView.setAdapter(adapter);
        }
    }


    //大棚数据json解析
    private DTU_data jsonMyDTUData(String result) {

        DTU_data dtu_data = new DTU_data();
        try {
            JSONArray array = new JSONArray(result);
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < array.length(); i++) {
                jsonObject = array.getJSONObject(i);
                dtu_data = new DTU_data(
                        jsonObject.getString("plotid"),
                        jsonObject.getString("datatime"),

                        jsonObject.getString("airtemp1"),
                        jsonObject.getString("airtemp2"),
                        jsonObject.getString("airtemp3"),

                        jsonObject.getString("airhumi1"),
                        jsonObject.getString("airhumi2"),
                        jsonObject.getString("airhumi3"),

                        jsonObject.getString("soiltemp1"),
                        jsonObject.getString("soiltemp2"),
                        jsonObject.getString("soiltemp3"),

                        jsonObject.getString("soilhumi1"),
                        jsonObject.getString("soilhumi2"),
                        jsonObject.getString("soilhumi3"),
                        jsonObject.getString("soilhumi4"),
                        jsonObject.getString("soilhumi5"),
                        jsonObject.getString("soilhumi6"),

                        jsonObject.getString("co2"),
                        jsonObject.getString("CO2_1"),
                        jsonObject.getString("CO2_2"),
                        jsonObject.getString("sundata1"),
                        jsonObject.getString("winopenl"));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("HjjTest" + dtu_inf.toString());
        return dtu_data;
    }

    //DataShowItem适配
    public ArrayList<HashMap<String, Object>> getItem(DTU_data dtu_data)
    {
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();

        if (dtu_data.getDatetime() == null) {
            d_odate.setText("查询失败");
            d_otime.setText("");
        }
        if (dtu_data.getDatetime() != null) {
            String t = dtu_data.getDatetime().substring(0,
                    dtu_data.getDatetime().length() - 2);
            String str[] = t.split(" ");
            d_odate.setText(str[0]);
            d_otime.setText(str[1]);
        }


    if(dtu_data.getAirtemp1()!=null && !dtu_data.getAirtemp1().equals("null"))
    {
        map = new HashMap<String, Object>();
        map.put("Dimg", R.drawable.airtemp);
        map.put("Dname", "空气温度1");
        map.put("Ddate", dtu_data.getAirtemp1());
        map.put("Dunit", "℃");
        list.add(map);
    }
    if(dtu_data.getAirtemp2()!=null && !dtu_data.getAirtemp2().equals("null"))
    {
        map = new HashMap<String, Object>();
        map.put("Dimg", R.drawable.airtemp);
        map.put("Dname", "空气温度2");
        map.put("Ddate", dtu_data.getAirtemp2());
        map.put("Dunit", "℃");
        list.add(map);
    }
    if(dtu_data.getAirtemp3()!=null && !dtu_data.getAirtemp3().equals("null"))
    {
        map = new HashMap<String, Object>();
        map.put("Dimg", R.drawable.airtemp);
        map.put("Dname", "空气温度3");
        map.put("Ddate", dtu_data.getAirtemp3());
        map.put("Dunit", "℃");
        list.add(map);
    }
    if(dtu_data.getAirhumi1()!=null && !dtu_data.getAirhumi1().equals("null"))
    {
        map = new HashMap<String, Object>();
        map.put("Dimg", R.drawable.airhumipp);
        map.put("Dname", "空气湿度1");
        map.put("Ddate", dtu_data.getAirhumi1());
        map.put("Dunit", "%");
        list.add(map);
    }
    if(dtu_data.getAirhumi2()!=null && !dtu_data.getAirhumi2().equals("null"))
    {
        map = new HashMap<String, Object>();
        map.put("Dimg", R.drawable.airhumipp);
        map.put("Dname", "空气湿度2");
        map.put("Ddate", dtu_data.getAirhumi2());
        map.put("Dunit", "%");
        list.add(map);
    }
    if(dtu_data.getAirhumi3()!=null && !dtu_data.getAirhumi3().equals("null"))
    {
        map = new HashMap<String, Object>();
        map.put("Dimg", R.drawable.airhumipp);
        map.put("Dname", "空气湿度3");
        map.put("Ddate", dtu_data.getAirhumi3());
        map.put("Dunit", "%");
        list.add(map);
    }

        //土壤温度
        if(dtu_data.getSoiltemp1()!=null && !dtu_data.getSoiltemp1().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soiltemp);
            map.put("Dname", "土壤温度1");
            map.put("Ddate", dtu_data.getSoiltemp1());
            map.put("Dunit", "℃");
            list.add(map);
        }
        if(dtu_data.getSoiltemp2()!=null && !dtu_data.getSoiltemp2().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soiltemp);
            map.put("Dname", "土壤温度2");
            map.put("Ddate", dtu_data.getSoiltemp2());
            map.put("Dunit", "℃");
            list.add(map);
        }
        if(dtu_data.getSoiltemp3()!=null && !dtu_data.getSoiltemp3().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soiltemp);
            map.put("Dname", "土壤温度3");
            map.put("Ddate", dtu_data.getSoiltemp3());
            map.put("Dunit", "℃");
            list.add(map);
        }

        //土壤湿度
        if(dtu_data.getSoilhumi1()!=null && !dtu_data.getSoilhumi1().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soilhumi);
            map.put("Dname", "土壤湿度1");
            map.put("Ddate", dtu_data.getSoilhumi1());
            map.put("Dunit", "%");
            list.add(map);
        }
        if(dtu_data.getSoilhumi2()!=null && !dtu_data.getSoilhumi2().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soilhumi);
            map.put("Dname", "土壤湿度2");
            map.put("Ddate", dtu_data.getSoilhumi2());
            map.put("Dunit", "%");
            list.add(map);
        }
        if(dtu_data.getSoilhumi3()!=null && !dtu_data.getSoilhumi3().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soilhumi);
            map.put("Dname", "土壤湿度3");
            map.put("Ddate", dtu_data.getSoilhumi3());
            map.put("Dunit", "%");
            list.add(map);
        }
        if(dtu_data.getSoilhumi4()!=null && !dtu_data.getSoilhumi4().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soilhumi);
            map.put("Dname", "土壤湿度4");
            map.put("Ddate", dtu_data.getSoilhumi4());
            map.put("Dunit", "%");
            list.add(map);
        }
        if(dtu_data.getSoilhumi5()!=null && !dtu_data.getSoilhumi5().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soilhumi);
            map.put("Dname", "土壤湿度5");
            map.put("Ddate", dtu_data.getSoilhumi5());
            map.put("Dunit", "%");
            list.add(map);
        }
        if(dtu_data.getSoilhumi6()!=null && !dtu_data.getSoilhumi6().equals("null"))
        {

            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.soilhumi);
            map.put("Dname", "土壤湿度6");
            map.put("Ddate", dtu_data.getSoilhumi6());
            map.put("Dunit", "%");
            list.add(map);
        }

        //二氧化碳浓度
        if(dtu_data.getCo2()!=null && !dtu_data.getCo2().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.co);
            map.put("Dname", "二氧化碳");
            map.put("Ddate", dtu_data.getCo2());
            map.put("Dunit", "PPM");
            list.add(map);
        }
        if(dtu_data.getCO2_1()!=null && !dtu_data.getCO2_1().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.co);
            map.put("Dname", "二氧化碳1");
            map.put("Ddate", dtu_data.getCO2_1());
            map.put("Dunit", "PPM");
            list.add(map);
        }
        if(dtu_data.getCO2_2()!=null && !dtu_data.getCO2_2().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.co);
            map.put("Dname", "二氧化碳2");
            map.put("Ddate", dtu_data.getCO2_2());
            map.put("Dunit", "PPM");
            list.add(map);
        }

        if(dtu_data.getSundata1()!=null && !dtu_data.getSundata1().equals("null"))
        {
            map = new HashMap<String, Object>();
            map.put("Dimg", R.drawable.light);
            map.put("Dname", "光照强度");
            map.put("Ddate", dtu_data.getSundata1());
            map.put("Dunit", "KLX");
            list.add(map);
        }

        //暂时无该条目需求
//        map = new HashMap<String, Object>();
//        map.put("Dimg", R.drawable.soilyanfen);
//        map.put("Dname", "风窗开关");
//        map.put("Ddate", dtu_data.getWinopenl());
//        map.put("Dunit", "mS/cm");
//        list.add(map);

        System.out.println(list);
        return list;

    }

    //************************* 折线图 ****************


    //折线图URL
    public String setURL(String type, String dtu, int number) {
        String URL;
        URL = path9 + dtu + "&type=" + type + "&number=" + number;
        return URL;
    }

    //Dialog LineChartView

    public void showDialog(String type, String unit, List<LineChartData> list) {
        LayoutInflater inflater = LayoutInflater.from(this.getActivity());
        final View view = inflater.inflate(R.layout.linechar, null);
        lineChartView = (LineChartView) view.findViewById(R.id.char_line);

        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(getActivity());

        String[] date = new String[list.size()];
        double[] data = new double[list.size()];

        for (int i = 0; i < list.size(); i++) {
            date[i] = list.get(i).getDatetime().toString().substring(11, 16);
            data[i] = list.get(i).getInfo();
        }
        System.out.println(date.length + " *************date.length");
        System.out.println(data.length + " *************date.length");

        lineChartView.setData(date, data, type, unit);
        lineChartView.setYMin_MaxValue();
        builder.setView(view)
                .setPositiveButton("关闭", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    //将字符转为 数据库属性名
    public String changeTYPE(String type) {
        System.out.println(type);
        String nt = null;
        switch (type) {
            case "空气温度1":
                nt = "airtemp1";
                break;
            case "空气温度2":
                nt = "airtemp2";
                break;
            case "空气温度3":
                nt = "airtemp3";
                break;

            case "空气湿度1":
                nt = "airhumi1";
                break;
            case "空气湿度2":
                nt = "airhumi2";
                break;
            case "空气湿度3":
                nt = "airhumi3";
                break;

            case "土壤温度1":
                nt = "soiltemp1";
                break;
            case "土壤温度2":
                nt = "soiltemp2";
                break;
            case "土壤温度3":
                nt = "soiltemp3";
                break;

            case "土壤湿度1":
                nt = "soilhumi1";
                break;
            case "土壤湿度2":
                nt = "soilhumi2";
                break;
            case "土壤湿度3":
                nt = "soilhumi3";
                break;
            case "土壤湿度4":
                nt = "soilhumi4";
                break;
            case "土壤湿度5":
                nt = "soilhumi5";
                break;
            case "土壤湿度6":
                nt = "soilhumi6";
                break;


            case "二氧化碳":
                nt = "co2";
                break;
            case "二氧化碳1":
                nt = "CO2_1";
                break;
            case "二氧化碳2":
                nt = "CO2_2";
                break;

            case "光照强度":
                nt = "sundata1";
                break;

//            case "风窗开关":
//                nt = "winopenl";
//                break;

            default:
                nt = null;
                break;
        }
        return nt;
    }

    public class lineAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            String[] info = strings[0].split("~");

            System.out.println("****************");
            System.out.println(info[0]);
            System.out.println(info[1]);
            System.out.println(info[2]);

            String result = sendPostMethod(info[0], "utf-8");
            return result + "~" + info[1] + "~" + info[2];
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            System.out.println(s);

            String[] info = s.split("~");

            System.out.println("****************");
            System.out.println(info[0]);
            System.out.println(info[1]);
            System.out.println(info[2]);
            ArrayList<LineChartData> list = null;
            if (!info[0].equals("fail")) {
                list = lineJSON(info[0]);
                if (list.size() != 0) {
                    showDialog(info[1], info[2], list);
                } else {
                    Toast.makeText(getActivity(), "折线图显示失败...", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getActivity(), "折线图显示失败...", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private ArrayList<LineChartData> lineJSON(String result) {
        ArrayList<LineChartData> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(result);
            JSONObject object = new JSONObject();

            for (int i = 0; i < array.length(); i++) {
                object = array.getJSONObject(i);

                LineChartData point = new LineChartData(object.getString("datetime"),
                        Double.parseDouble(object.getString("value")));
                list.add(point);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Collections.reverse(list);
        return list;

    }


}
